package com.bank.handler;

import com.bank.constant.MessageConstant;
import com.bank.exception.BaseException;
import com.bank.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        if (message.contains("Duplicate entry") && message.contains("username")) {
            return Result.error(MessageConstant.USERNAME_EXIST);
        } else if (message.contains("Duplicate entry") && message.contains("id_number")) {
            return Result.error(MessageConstant.ID_NUMBER_USED);
        } else {
            return Result.error(MessageConstant.DATABASE_ERROR);
        }
    }

    @ExceptionHandler
    public Result handleConstraintViolationException(MethodArgumentNotValidException ex) {
        // 获取绑定结果，提取字段和对应的错误消息
        BindingResult bindingResult = ex.getBindingResult();
        String errorMessage = bindingResult.getFieldErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage) // 提取字段名和自定义消息
                .collect(Collectors.joining("; ")); // 拼接成单个字符串返回

        return Result.error(errorMessage); // 返回精简后的错误信息
    }
}
